//
//  YAYIEditNameViewController.m
//  yayi
//
//  Created by Veer on 16/3/18.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIModifyAccountViewController.h"
#import "YAYILoginViewController.h"
#import "YAYISettingSectionModel.h"
#import "YAYISettingItemModel.h"


@interface YAYIModifyAccountViewController()<UIAlertViewDelegate>

@property (nonatomic, weak) UITextField *editTF;

@property (nonatomic, weak) UITextField *oldPasswordTF;
@property (nonatomic, weak) UITextField *modifiedpasswordTF;

@end

@implementation YAYIModifyAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"密码修改";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = YAYICellLineColor;
    
    // 初始化导航栏
    [self setupNav];
    
    // 初始化子控件
    //[self setupSubview];
    [self setupSection0];
}



- (void)setupSection0
{
    YAYISettingItemModel *item0 = [YAYISettingItemModel itemWithIcon:nil name:@"密码修改"];
    
    __block typeof(self) weakself = self;
    item0.executeOperation = ^(NSIndexPath *indexPath){
        
        YAYIModifyAccountViewController *editVc = [[YAYIModifyAccountViewController alloc] init];
        editVc.indexPath = indexPath;
        
        [weakself.navigationController pushViewController:editVc animated:YES];
    };
    
    YAYISettingSectionModel *section0 = [[YAYISettingSectionModel alloc]init];
    section0.itemArray = @[item0];
    
    [self.sectionArray addObject:section0];
}


- (void)setupNav
{
    // left button
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    leftBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    
    leftBtn.bounds = CGRectMake(0, 0, 40, 20);
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    // left button
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    
    rightBtn.bounds = CGRectMake(0, 0, 40, 20);
    [rightBtn addTarget:self action:@selector(saveClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
}

- (void)setupSubview
{
    UITextField *textFiled = [[UITextField alloc] init];
    textFiled.backgroundColor = [UIColor whiteColor];
    textFiled.clearButtonMode = UITextFieldViewModeAlways;
    textFiled.frame = CGRectMake(0, 20, SCREEN_width, 44);
    self.editTF = textFiled;
    
    [self.view addSubview:textFiled];
}

/**
 *  显示提示框
 */
- (void)showHubWith:(NSString *)messageStr isBack:(BOOL)isBack
{
    YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view.window];
    [hud setMessage:messageStr];
    [self.view.window addSubview:hud];
    [hud removeFromSuperview:YES time:1.0 isHinden:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (isBack) {
            [self backAction];
        }
        
    });
    
}


#pragma mark 按钮相应方法
- (void)saveClick:(UIButton *)sender
{
    YAYILog(@"save: indexPath:%ld %ld", self.indexPath.row, self.indexPath.section);
    
    NSString *oldPwd = self.oldPasswordTF.text;
    NSString *newPwd = self.modifiedpasswordTF.text;
    
    if (newPwd.length < 6) {
        
        [SVProgressHUD showImage:nil status:@"\n\n新密码长度不能少于6位\n\n"];
        return;
    }else if (newPwd.length > 16){
        
        [SVProgressHUD showImage:nil status:@"\n\n新密码长度不能大于16位\n\n"];
        return;
    }
    
    
    if (oldPwd.length == 0) {
        [SVProgressHUD showImage:nil status:@"\n\n 请输入当前密码     \n\n"];
        return;
    }else if (newPwd.length == 0){
        [SVProgressHUD showImage:nil status:@"\n\n 请输入新密码     \n\n"];
        return;
    }
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (oldPwd.length > 0 && newPwd.length > 0) {
        param[@"oldPwd"] = oldPwd;
        param[@"newPwd"] = newPwd;
        
        YAYILog(@"param:%@", param);
        
        [YAYINetWorking postJsonSerilizeWithURL:resetPwd_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
            if (error == nil) {
                YAYILog(@"返回：%@", dict);
                
                if (![dict isKindOfClass:[NSNull class]] && [dict[@"status"] isEqualToString:@"success"]) {
                    

                    [SVProgressHUD showSuccessWithStatus:@"用户密码设置成功！\n请重新登录"];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        YAYILoginViewController *loginView = [[YAYILoginViewController alloc] init];
                        [self presentViewController:loginView animated:YES completion:nil];
                        loginView.loginSuccessOperation = ^{
                            
                            [self.navigationController popToRootViewControllerAnimated:YES];
                        };
                        loginView.cancelOperation = ^{
                            UIViewController *controller = self.navigationController.viewControllers[0];
                            [controller.tabBarController setSelectedIndex:0];
                            [self.navigationController popToViewController:controller animated:YES];
                        };
                    });
                    
                }else if([dict[@"status"] isEqualToString:@"redirect"]){
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"登录失效，请重新登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
                    [alert show];
                }else{
                    if ([dict[@"message"] rangeOfString:@"密码不正确"].location != NSNotFound){
                        
                        [SVProgressHUD showErrorWithStatus:@"原始密码不正确\n设置失败。"];
                        
                    }
                    return ;
                }
                
                
            }else{
                NSString *message = responseError[@"message"];
                [SVProgressHUD showErrorWithStatus:message];
            }
        }];

    }
    
    
    if ([self.delegate respondsToSelector:@selector(editNameDidChanged:indexPath:)]) {
        
        if (self.editTF.text.length > 0) {
            [self.delegate editNameDidChanged:self.editTF.text indexPath:self.indexPath];
        }
    }
}


-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];

}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    YAYILoginViewController *loginView = [[YAYILoginViewController alloc] init];
    [self presentViewController:loginView animated:YES completion:nil];
    loginView.loginSuccessOperation = ^{
        [self.navigationController popToRootViewControllerAnimated:YES];
    };
}
#pragma mark - tableView数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    UITextField *textField = [[UITextField alloc] init];
    textField.font = [UIFont systemFontOfSize:15];
    textField.secureTextEntry = YES;
    textField.frame = CGRectMake(20, 0, SCREEN_width, 50);
    textField.tag = indexPath.row;
    
    if (0 == indexPath.row) {
        textField.placeholder = @"输入当前密码";
        self.oldPasswordTF = textField;
    }else if(1 == indexPath.row){
        textField.placeholder = @"输入新密码";
        self.modifiedpasswordTF = textField;
    }
    
    [cell.contentView addSubview:textField];
    
    return cell;
}



@end
